package com.sanda.androidcourse.chapter07;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;

import java.util.ArrayList;
import java.util.List;

public class StudentProvider extends ContentProvider {

    private final List<Student> studentList = new ArrayList<>();
    public static final String AUTHORITY = "com.sanda.androidcourse";
    private static final String PATH_STUDENTS = "students";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + PATH_STUDENTS);


    private static final int STUDENTS = 1;
    private static final int STUDENT_ID = 2;
    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        uriMatcher.addURI(AUTHORITY, PATH_STUDENTS, STUDENTS);
        uriMatcher.addURI(AUTHORITY, PATH_STUDENTS + "/#", STUDENT_ID);
    }

    public StudentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        // at the given URI.
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public boolean onCreate() {
        studentList.add(new Student(1, "Alice", 22));
        studentList.add(new Student(2, "Bob", 23));
        studentList.add(new Student(3, "Charlie", 21));
        //true表示返回数据成功，系统可以使用
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        //MatrixCursor适用于数据存储在内存中的情况
        MatrixCursor cursor = new MatrixCursor(new String[]{"_id", "name", "age"});    // 仅支持查询所有学生
        switch (uriMatcher.match(uri)) {
            case STUDENTS:
                for (Student student : studentList) {
                    cursor.addRow(new Object[]{student.id, student.name, student.age});
                }
                break;
            case STUDENT_ID:
                int id = Integer.parseInt(uri.getLastPathSegment());
                for (Student student : studentList) {
                    if (student.id == id) {
                        cursor.addRow(new Object[]{student.id, student.name, student.age});
                        break;
                    }
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        return 0;
    }
}